<!--
 * @Description: 设计会议
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-08-03 14:44:50
 * @LastEditTime: 2021-08-12 11:38:50
 * @FilePath: \cscec-pms-admin\src\views\design\training\trainingConference\components\page.vue
-->
<template>
  <div>
    <!-- 搜索 -->
    <searchData
      :search-data="pageName==='trainingConference'?searchOption2:searchOption"
      @search="search"
    />
    <!-- 搜索 -->
    <!-- 会 -->
    <a-card>
      <!-- 表格操作 -->
      <div class="table-operator">
        <!-- <title-name :title="$route.meta.title" /> -->
      </div>
      <!-- 表格操作 -->
      <!-- 表格 -->
      <list-table
        ref="table"
        :columns="columns"
        :request="loadData"
        :page-keys=" ['pageNum', 'pageSize', 'total']"
        :export-config="{ use: pageName === 'trainingConference',select: '设计培训管理会',all: '设计培训管理会'}"
      >
        <template slot="prefix" v-if="hideBuquBtn()">
          <a-button

            type="primary"
            icon="plus"
            @click="handleAdd"
          >
            新增会议
          </a-button>
          <a-button
            v-if="pageName === 'analyseConference'"
            v-btnPermission="'ds_017_not_01'"
            type="primary"
            icon="message"
            @click="analyseVisible = !analyseVisible"
          >
            复盘通知
          </a-button>
        </template>
        <span
          slot="status"
          slot-scope="text,record"
        >
          <list-status
            :status="record.meetingStatus"
            conversion="en"
          />
        </span>
        <span
          slot="operation"
          slot-scope="text,record"
        >
          <MoreButton>
          <template
            v-if="record.meetingStatus === '20'"
            v-btnPermission="btnPermission[pageName].detail"
          >
            <a @click="handleOperation(record,'detail')">会议详情</a>
          </template>
          <template
            v-if="record.meetingStatus === '30' || record.meetingStatus === '50'"
            v-btnPermission="btnPermission[pageName].join"
          >
            <a @click="handleOperation(record,'join')">进入会议</a>
            <a-divider
              v-if="record.meetingStatus === '50'"
              type="vertical"
            />
          </template>
          <template
            v-if="record.meetingStatus === '40' || record.meetingStatus === '35'"
            v-btnPermission="btnPermission[pageName].view"
          >
            <a @click="handleOperation(record,'view')">查看会议</a>
            <a-divider type="vertical" />
          </template>
          <template v-if="pageName==='trainingConference'">
            <a
              v-if="record.meetingStatus === '35' || record.meetingStatus === '40' || record.meetingStatus === '50'"
              @click="hadnleApprova(record)"
            >审批信息</a>
          </template>
            </MoreButton>
        </span>
      </list-table>
      <!-- 表格 -->
    </a-card>
    <!-- 会 -->
    <!-- 复盘通知模态框 -->
    <BaseModal
      :visible="analyseVisible"
      title="复盘通知"
      centered
      :width="900"
      @cancel="analyseVisible = false"
    >
      <custom-form
        ref="form"
        :is-validate="true"
        :edit-model="''"
        :rules="rules"
        :form="form"
        :form-list="formOption"
        @selectOrg="selectOrg"
        class="requiredFormItem"
      >
        <template slot="informStaff">
          <div class="analyse-conference-btn">
            <BaseInput
              v-model="form.informStaff"
              placeholder="请选择"
              disabled
            />
            <a-button
              type="primary"
              @click="personVisible = true"
            >
              选择
            </a-button>
          </div>
        </template>
      </custom-form>
      <template slot="footer">
        <a-button @click="analyseVisible = false">
          取消
        </a-button>
        <a-button
          :loading="submitLoading"
          type="primary"
          @click="handleAnalyse"
        >
          提交
        </a-button>
      </template>
    </BaseModal>
    <!-- 复盘通知模态框 -->
    <!-- 选择通知人员模态框 -->
    <SelectPersonModal
      :personsList="persons"
      :visible.sync="personVisible"
      :is-mutilple="true"
      @confirmSelect="confirmSelects"
    />
    <!-- 选择通知人员模态框 -->
  </div>
</template>
<script>
import { statusList, searchOption, searchOption2, columns, meetingTypeNumber, btnPermission } from './model.js'
import listStatus from '@/components/list_status/meeting_status'
import BaseModal from '@/components/BaseModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import SelectPersonModal from '@/components/SelectPersonModal'
import training from '@/api/design/training'
import Vue from 'vue'
import { getAuditProject } from '@/api/themeChoose/themeChoose'

export default {
  name: 'Page',
  props: {
    // 页面名字
    pageName: {
      type: String,
      default: ''
    },
    // 页面父级名字
    pageParent: {
      type: String,
      default: ''
    }
  },
  components: {
    listStatus,
    BaseModal,
    SelectPersonModal
  },
  data() {
    return {
      // 用户信息
      userInfo: Vue.getAcloudProvider().getUserInfo(),
      // 状态列表
      statusList,
      // 搜搜列表
      searchOption,
      searchOption2,
      // 表头
      columns,
      // 查询参数
      searchData: {},
      // 表格加载
      tableLoading: false,
      // 表格数据
      table: [],
      // 表格总数
      total: 0,
      // 表格选中项
      selectedRowKeys: [],
      // 表格复选
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys) => {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      loadData: async (q) => {
        const params = Object.assign(q, { param: this.searchData })
        if (this.searchData?.startEndDate?.length > 0) {
          params.param.startTime = this.searchData.startEndDate[0].format('YYYY-MM-DD') || void 0
          params.param.endTime = this.searchData.startEndDate[1].format('YYYY-MM-DD') || void 0
        }
        params.param.meetingType = meetingTypeNumber[this.pageName]
        delete params.startEndDate
        let res = await training.getPageMeeting(params)
        if (res.code === 200) {
          return { code: 200, data: res.data.list, ...res.data }
        }
        return { code: 200, data: [] }
      },

      // 表格选中导出中
      exportLoading: false,
      // 复盘通知模态框显示隐藏
      analyseVisible: false,
      // 复盘通知表单
      form: {
        projectId: '',
        informStaff: ''
      },
      // 复盘通知提交loading
      submitLoading: false,
      // 选择人员模态框显示隐藏
      personVisible: false,
      // 通知人员
      persons: [],
      rules: {
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        informStaff: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      // 按钮权限
      btnPermission
    }
  },
  computed: {
    // 表单配置
    formOption() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled: false,
          isQueryProjecDetail: false
        },
        // {
        //   label: '分公司',
        //   keyName: 'branchComId',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     ref: 'SelectSubCompany',
        //     autoSelected: this.$route.query.pageType === 'add'
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }],
        //   span: 12
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectId',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联
        //     ref: 'SelectProject',
        //     autoSelected: this.$route.query.pageType === 'add',
        //     keyValue: 'branchComId',
        //     form: this.form
        //   },
        //   rules: [{ required: true, message: '请选择', trigger: 'change' }],
        //   span: 12
        // },
        {
          label: '通知人员',
          keyName: 'informStaff',
          slot: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          span: 24
        }
      ]
    },
  },
  watch: {
    analyseVisible: {
      handler(val) {
        if (!val) {
          this.form = {}
          this.persons = []
        }
      }
    },
    // 通知人员
    persons: {
      handler(val) {
        this.form.informStaff = val.map((el) => el.name).join(',')
        this.$refs.form.clearValidate(['informStaff'])
      }
    }
  },
  methods: {
    confirmSelects(val) {
      this.persons = val
    },
    selectOrg(val) {
      if(val.length>1) {
        this.form.branchComId = val[val.length - 2].orgId
      }
    },
    /**
     * @description: 搜索
     * @param {Object} value 搜索数据
     * @return {Void}
     */
    search(value) {
      this.searchData = value || {}
      this.$refs.table.getData(null, true)
    },
    /**
     * @description: 新增会议
     * @param {Void}
     * @return {Void}
     */
    async handleAdd() {
      if (this.pageName === 'planningJoint') {
        if (this.userInfo.currentPost.code === 'PD') {
          const { data } = await getAuditProject({
            deptOrgIds: [this.userInfo.currentPost.id],
            designTypeNames: ['a1类', 'a2类', 'a3类']
          })
          if (data.length === 0) {
            this.$message.warning('该项目不为a类项目，不能进行设计策划联合评审会')
          } else {
            this.$router.push({
              path: `/project/design/${this.pageParent}/${this.pageName}/add`,
              query: {
                id: '',
                pageName: this.pageName
              }
            })
          }
        } else {
          this.$router.push({
            path: `/project/design/${this.pageParent}/${this.pageName}/add`,
            query: {
              id: '',
              pageName: this.pageName
            }
          })
        }
      } else {
        this.$router.push({
          path: `/project/design/${this.pageParent}/${this.pageName}/add`,
          query: {
            id: '',
            pageName: this.pageName
          }
        })
      }
    },

    /**
     * @description: 处理表格导出数据
     * @param {Array} data 表格数据
     * @return {Object} {list:表格数据，columns：表头}
     */
    handleTableDataToExport(data) {
      const list = (data || []).map((el, index) => {
        const item = JSON.parse(JSON.stringify(el))
        item.index = index + 1
        item.status = statusList.find((el) => el.value === item.status).label
        return item
      })
      const columns = [
        {
          title: '序号',
          dataIndex: 'index'
        },
        {
          title: '会议名称',
          dataIndex: 'meetingName'
        },
        {
          title: '会议类型',
          dataIndex: 'meetingType'
        },
        {
          title: '所属分公司',
          dataIndex: 'branchComName'
        },
        {
          title: '所属项目',
          dataIndex: 'projectName'
        },
        {
          title: '召开时间',
          dataIndex: 'startTime'
        },
        {
          title: '参会人数',
          dataIndex: 'meetingCount'
        },
        {
          title: '创建人',
          dataIndex: 'creatorName'
        },
        {
          title: '状态',
          dataIndex: 'status'
        }
      ]
      return {
        list,
        columns
      }
    },
    /**
     * @description: 导出选中
     * @param {Void}
     * @return {Void}
     */
    handleSelectExport() {
      this.exportLoading = true
      try {
        const data = this.table.filter((el) => this.selectedRowKeys.includes(el.id))
        const { list, columns } = this.handleTableDataToExport(data)
        this.$refs.exportBtn.generateExcel(list, { columns }, 0)
      } catch (error) {
        console.log(error)
      } finally {
        this.exportLoading = false
      }
    },
    /**
     * @description: 导出全部
     * @param {Void}
     * @return {Void}
     */
    async handleAllExport() {
      if (!this.total) {
        this.$message.warning('没有可导出数据')
        return
      }
      this.exportLoading = true
      try {
        const params = Object.assign(
          {},
          {
            pageNo: 1,
            pageSize: this.total
          },
          { param: this.searchData }
        )
        if (this.searchData?.startEndDate?.length > 0) {
          params.param.startTime = this.searchData.startEndDate[0].format('YYYY-MM-DD') || void 0
          params.param.endTime = this.searchData.startEndDate[1].format('YYYY-MM-DD') || void 0
        }
        const { data } = await otherTypesContract.findListByMain(params)
        const { list, columns } = this.handleTableDataToExport(data)
        this.$refs.exportBtn.generateExcel(list, { columns }, 0)
      } catch (error) {
        console.log(error)
      } finally {
        this.exportLoading = false
      }
    },
    /**
     * @description: 会议操作
     * @param {object} record
     * @param {string} pageType
     * @return {void}
     */
    handleOperation(record, pageType) {
      this.$router.push({
        path: `/project/design/${this.pageParent}/${this.pageName}/operation`,
        query: {
          id: record.id,
          meetingName: record.meetingName,
          pageName: this.pageName,
          pageType
        }
      })
    },
    /**
     * @description: 会议复盘通知
     * @return {void}
     */
    handleAnalyse() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          training
            .replay({
              projectId: this.form.projectId,
              userIdList: this.persons.map((el) => el.userId).join(',')
            })
            .then(({ code, message }) => {
              if (code === 200) {
                this.$message.success('通知成功')
                this.analyseVisible = false
              } else {
                this.$message.warning(message)
              }
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },
    /**
     * @description: 审批信息
     * @param {object} record
     * @return {void}
     */
    hadnleApprova(record) {
      this.$bus.$emit('showApprovalDetailsDialog', record.id)
    }
  }
}
</script>
<style lang="less">
.analyse-form {
  .ant-select:not(.ant-select-disabled) .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
}
</style>
<style lang="less" scoped>
@deep: ~'>>>';
.analyse-conference-btn {
  display: flex;
  align-items: center;
  .BaseInput-container {
    flex: 1;
    margin-right: 10px;
  }
  .ant-btn {
    height: 28px;
  }
}
</style>
